<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增处理单</div>
            <div v-else-if="route.query?.id">
              处理单详情
              <el-tag>{{ form.code }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="120px"
            >
              <!-- <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="上班日期" prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      readonly
                      v-model="form.createTime"
                      type="date"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="机台" prop="machineName">
                    <el-input
                      v-model="form.machineName"
                      readonly
                      placeholder="请选择机台"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="处理方式" prop="disposeWay">
                    <el-select
                      style="width: 100%"
                      v-model="form.disposeWay"
                      placeholder="请选择处理方式"
                    >
                      <el-option
                        v-for="item in ems_dispose_way"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row> -->
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="类别" prop="disposeType">
                    <el-select
                      style="width: 100%"
                      v-model="form.disposeType"
                      placeholder="请选择类别"
                    >
                      <el-option
                        v-for="item in quality_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="金额" prop="forfeit">
                    <el-input
                      v-model="form.forfeit"
                      type="number"
                      readonly
                      placeholder="自动合计"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="审核意见">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="相关罚款人员" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">相关罚款人员</span>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddmesQualityUserList"
          >
            选择人员
          </el-button>
          <div class="order-form">
            <el-form
              :disabled="flag"
              :model="data"
              ref="mesQualityUserListForm"
              class="data-form"
            >
              <el-table
                :data="data.mesQualityUserList"
                ref="mesQualityUserListRef"
                border
                :header-cell-class-name="mustPeople"
                :row-class-name="tableRowClassName"
                :summary-method="getSummaries"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="员工名称"
                  min-width="100"
                  prop="name"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="员工工号"
                  min-width="160"
                  prop="no"
                  align="center"
                ></el-table-column>

                <!-- <el-table-column
                  label="计件工资"
                  min-width="160"
                  prop="wagesPiece"
                  align="center"
                ></el-table-column> -->
                <!-- <el-table-column label="补助工资" min-width="160" prop="wagesSubsidy"
                                  align="center"></el-table-column>
                                  <el-table-column label="合计工资" min-width="160" prop="wagesSum"
                                  align="center"></el-table-column> -->
                <el-table-column
                  label="罚款(元)"
                  min-width="150"
                  prop="forfeit"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.forfeit"
                      type="number"
                      placeholder="请输入罚款(元)"
                    >
                      <template #append>元</template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!flag"
                  align="center"
                  width="80"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeletePeople(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="完成工作量明细" name="4">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">质量明细</span>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddOrderList"
          >
            选择生产单
          </el-button>
          <div class="order-form">
            <el-table
              ref="mesQualityWorkListForm"
              :data="data.mesQualityWorkList"
              border
            >
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <!-- <el-table-column
                label="类型"
                align="center"
                width="80"
                :show-overflow-tooltip="true"
                prop="type"
              >
                <template v-slot="{ row }">
                  <el-tag :type="row.type == 1 ? 'success' : ''" effect="dark">
                    {{ row.type == 1 ? "封面" : "内文" }}
                  </el-tag>
                </template>
              </el-table-column> -->
              <el-table-column
                label="生产单编码"
                width="150"
                align="center"
                :show-overflow-tooltip="true"
                prop="produceNo"
              ></el-table-column>
              <el-table-column
                label="出版编码"
                width="100"
                prop="pubNo"
                align="center"
              ></el-table-column>
              <el-table-column
                label="书刊名称"
                min-width="160"
                prop="bookName"
                align="center"
              ></el-table-column>
              <el-table-column
                label="发货品种"
                min-width="160"
                prop="shipmentType"
                align="center"
              ></el-table-column>
              <el-table-column
                label="版材备注"
                min-width="160"
                prop="remark"
                align="center"
              ></el-table-column>
              <el-table-column
                label="创建人"
                width="100"
                prop="createBy"
                align="center"
              ></el-table-column>
              <el-table-column
                label="下单日期"
                width="100"
                align="center"
                :show-overflow-tooltip="true"
                prop="orderTime"
              >
                <template v-slot="{ row }">
                  {{ row.orderTime ? row.orderTime.split("T")[0] : "" }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchPeoples
      :visible="searchPeopleVisible"
      :peopleSelectList="peopleSelectList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></SearchPeoples>
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
  </div>
</template>

<script setup>
import SearchPeoples from "@/components/SearchPeoples";
import orderList from "./orderList.vue";
import { getByIdQuality, addQuality } from "@/api/production/quality.js";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { toNumber } from "@/utils/ruoyi";
import { nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const searchPeopleVisible = ref(false);
const pieceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const orderListOpen = ref(false);
const orderSelectList = ref([]);
const mesQualityWorkListForm = ref(null);
const btnLoading = ref(false);
const activeNames = ["1", "2", "3", "4"];
const userRef = ref(null);
const mesQualityUserListForm = ref(null);
const flag = ref(false);
const totalWagesSum = ref(0);
const totalAmount = ref(0);
const totalAmountH = ref(0);
const params = ref({});
const data = reactive({
  reportCareList: [], // 保养
  mesQualityUserList: [], // 人员
  mesQualityWorkList: [], // 完成
  form: {
    type: "1",
  },
  rules: {
    disposeType: [
      { required: true, message: "类别不能为空", trigger: "change" },
    ],
  },
});
nextTick(() => {
  form.value.createBy = userInfo.name;
});

const {
  ems_dispose_way,
  ems_produce_finish_size,
  ems_produce_book_size,
  ems_order_binding_mode,
  mes_paper_package,
  ems_order_print_color,
  mes_paper_specs,
  mes_paper_type,
  quality_type,
} = proxy.useDict(
  "ems_dispose_way",
  "mes_paper_package",
  "ems_order_print_color",
  "mes_paper_type",
  "ems_order_binding_mode",
  "ems_produce_finish_size",
  "ems_produce_book_size",
  "mes_paper_specs",
  "quality_type"
);
const { form, rules, reportCareList, mesQualityUserList, mesQualityWorkList } =
  toRefs(data);
if (route.query?.id) {
  getByIdQuality({ id: route.query.id }).then((res) => {
    Object.assign(form.value, { ...res.data });
    mesQualityUserList.value = res.data.mesQualityUserList;
    mesQualityWorkList.value = res.data.mesQualityWorkList;
    // if (route.query.audit) {
    //   flag.value = true;
    // }
    if (route.query.info) {
      flag.value = true;
    }
  });
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `$ ${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "forfeit") {
        totalWagesSum.value = Number(sums[index].split("$")[1]);
        form.value.forfeit = totalWagesSum.value; //主表中的金额
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.reportDate = `${year}-${month}-${day} `;
  form.value.dutyDate = `${year}-${month}-${day} `;
};
getCurrentDateTime();

//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
};

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 选择人员
const handleAddmesQualityUserList = () => {
  peopleSelectList.value = mesQualityUserList.value;
  searchPeopleVisible.value = true;
};
// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(mesQualityUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      mesQualityUserList.value.push({
        ...item,
        no: item.code,
      });
      codeSet.add(item.id);
    }
  });
  //   mesQualityUserList.value = mesQualityUserList.value.filter((item) =>
  //     row.some((rowItem) => rowItem.id === item.id)
  //   );
  searchPeopleVisible.value = false;
};

const handleAddOrderList = () => {
  orderListOpen.value = true;
};
const changeOrderData = (row) => {
  row.orderTime = row.submitDate;
  mesQualityWorkList.value = [row];
  orderListOpen.value = false;
};

// 删除
const handleDeletePeople = (row, index) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    if (row.id) {
      mesQualityUserList.value = mesQualityUserList.value.filter(
        (item) => item.id !== row.id
      );
      handleTotalCount();
      proxy.$modal.msgSuccess("删除成功");
    }
  });
};

// 保存
const submitForm = async () => {
  btnLoading.value = true;
  try {
    await userRef.value.validate();
    if (mesQualityUserList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写相关罚款人员明细`,
        type: "warning",
      });
    }

    if (mesQualityWorkList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写质量量明细`,
        type: "warning",
      });
    }
    clearId(mesQualityUserList.value, "id");
    if (route.query?.id) {
      clearId(mesQualityWorkList.value, "id");
      await addQuality({
        ...form.value,
        mesQualityUserList: mesQualityUserList.value,
        mesQualityWorkList: mesQualityWorkList.value,
      });
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      goBack();
    } else {
      // 新增
      form.value.status = 0; //0:未审核 1：已审核  2：审核未通过
      await addQuality({
        ...form.value,
        mesQualityUserList: mesQualityUserList.value,
        mesQualityWorkList: mesQualityWorkList.value,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    btnLoading.value = false;
  }
};
// 审核
const handleAudit = () => {
  form.value.status = 2;
  addQuality({
    ...form.value,
    mesQualityUserList: mesQualityUserList.value,
    mesQualityWorkList: mesQualityWorkList.value,
  }).then((res) => {
    ElMessage({
      message: "提交成功",
      type: "success",
    });
    goBack();
  });
};
</script>

<style lang="scss" scoped>
.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}
</style>
